#include "sqlite_conn.hpp"
#include <mutex>


using namespace std;


using namespace ormpp;
namespace bz
{
	std::mutex db_mutex_;
	sqlite_conn::sqlite_conn()
		:db_conn_(new ormpp::dbng<ormpp::sqlite>),
		used_(false)
	{

	}

	bool sqlite_conn::init(std::string path, std::string edition)
	{
		string db_path = path + "/conf/xd_data.db";
		if (edition == "v2") {
			db_path = path + "/conf/multi_v2.db";
		}

		return db_conn_->connect(db_path.c_str());
	}


	ormpp::dbng<ormpp::sqlite>* sqlite_conn::get()
	{
		std::unique_lock<std::mutex> lock(mutex_);
		while (used_)
		{
			if (condition_.wait_for(lock, std::chrono::seconds(3)) == std::cv_status::timeout) {
				//timeout
				//WLOG << "sqlite_conn::get timeout used_= "<< used_;
				return nullptr;
			}
			//this_thread::sleep_for(100ms);
		}
		used_ = true;
		return db_conn_;
	}

	void sqlite_conn::return_back()
	{
		std::unique_lock<std::mutex> lock(mutex_);
		used_ = false;
		lock.unlock();
		condition_.notify_one();
		//WLOG << "sqlite_conn::return_back()";
	}

	ormpp::dbng<ormpp::sqlite>* sqlite_conn::get_conn()
	{
		return sqlite_conn::instance()->get();
	}

}
